const { app } = require('electron');
const path = require('path');
const fs = require('fs');

/**
 * 轻量级异步日志工具
 * 避免同步I/O阻塞主进程
 */
class Logger {
    constructor(customPath = null) {
        const defaultLogPath = path.join(app.getPath('userData'), 'app.log');
        this.logPath = customPath || defaultLogPath;
        this.queue = [];
        this.isWriting = false;

        // 确保日志目录存在
        const logDir = path.dirname(this.logPath);
        if (!fs.existsSync(logDir)) {
            fs.mkdirSync(logDir, { recursive: true });
        }

        // 创建可写流（append模式）
        this.stream = fs.createWriteStream(this.logPath, { flags: 'a' });

        // 初始化日志
        this._write('INFO', '=================================');
        this._write('INFO', 'Logger initialized');
        this._write('INFO', `Log file: ${this.logPath}`);
        this._write('INFO', '=================================');
    }

    /**
     * 内部写入方法（使用队列避免阻塞）
     */
    _write(level, message, ...args) {
        const timestamp = new Date().toISOString();

        // 处理参数
        const formattedArgs = args.map(arg => {
            if (typeof arg === 'object') {
                try {
                    return JSON.stringify(arg);
                } catch (e) {
                    return String(arg);
                }
            }
            return String(arg);
        }).join(' ');

        const fullMessage = formattedArgs ? `${message} ${formattedArgs}` : message;
        const logLine = `[${timestamp}] [${level}] ${fullMessage}\n`;

        // 添加到队列
        this.queue.push(logLine);

        // 异步处理队列
        this._processQueue();

        // 同时输出到控制台（开发模式）
        if (process.env.NODE_ENV === 'development' || !app.isPackaged) {
            const consoleMethod = level === 'ERROR' ? console.error : console.log;
            consoleMethod(`[${level}]`, fullMessage);
        }
    }

    /**
     * 异步处理日志队列
     */
    _processQueue() {
        if (this.isWriting || this.queue.length === 0) {
            return;
        }

        this.isWriting = true;
        setImmediate(() => {
            const batch = this.queue.splice(0, 10); // 每次最多处理10条
            batch.forEach(line => this.stream.write(line));
            this.isWriting = false;

            // 如果还有待处理的日志，继续处理
            if (this.queue.length > 0) {
                this._processQueue();
            }
        });
    }

    /**
     * 记录信息日志
     */
    info(message, ...args) {
        this._write('INFO', message, ...args);
    }

    /**
     * 记录错误日志
     */
    error(message, ...args) {
        this._write('ERROR', message, ...args);
    }

    /**
     * 记录警告日志
     */
    warn(message, ...args) {
        this._write('WARN', message, ...args);
    }

    /**
     * 记录调试日志（仅开发模式）
     */
    debug(message, ...args) {
        if (process.env.NODE_ENV === 'development' || !app.isPackaged) {
            this._write('DEBUG', message, ...args);
        }
    }

    /**
     * 关闭日志流
     */
    close() {
        return new Promise((resolve) => {
            // 等待队列清空
            const checkQueue = () => {
                if (this.queue.length === 0 && !this.isWriting) {
                    this.stream.end(() => {
                        this.info('Logger closed');
                        resolve();
                    });
                } else {
                    setTimeout(checkQueue, 100);
                }
            };
            checkQueue();
        });
    }
    reinitialize(newLogPath) {
        return new Promise((resolve) => {
            // 等待队列清空
            const checkQueue = () => {
                if (this.queue.length === 0 && !this.isWriting) {
                    // 关闭旧流
                    const oldPath = this.logPath;
                    this.stream.end(() => {
                        // 更新路径
                        this.logPath = newLogPath;

                        // 确保目录存在
                        const logDir = path.dirname(this.logPath);
                        if (!fs.existsSync(logDir)) {
                            fs.mkdirSync(logDir, { recursive: true });
                        }

                        // 创建新流
                        this.stream = fs.createWriteStream(this.logPath, { flags: 'a' });

                        // 记录路径变更
                        this._write('INFO', '=================================');
                        this._write('INFO', `Logger reinitialized from ${oldPath} to ${newLogPath}`);
                        this._write('INFO', '=================================');

                        resolve();
                    });
                } else {
                    setTimeout(checkQueue, 100);
                }
            };
            checkQueue();
        });
    }
}

// 单例模式
let loggerInstance = null;

function getLogger() {
    if (!loggerInstance) {
        loggerInstance = new Logger();
    }
    return loggerInstance;
}

module.exports = getLogger();
